import { TableCell } from "@mui/material";
import { Col, Row, Tooltip } from "antd";
import { SortOrder } from "antd/es/table/interface";
import { ReactElement, useMemo, useState } from "react";
import { Resizable, ResizeCallbackData } from "react-resizable";
import { getTableSortIcon } from "../../common";
import { IMUIColumnType } from "../common";

const TABLE_COL_MIN_WIDTH = 50

const getSortTitle = (sorter: boolean | { multiple?: boolean | number }, sortOrder: SortOrder) => {
    if (!sorter) return
    if (!sortOrder) return "点击升序"
    if (sortOrder === "ascend") return "点击降序"
    return "取消排序"
}

interface IResizableTitle {
    column: any;
    onResize: (e: any, { size }: ResizeCallbackData) => void;
    children: ReactElement;
    resizeDisable?: boolean; // 禁用表头拖拽
    colResizeDisable?: boolean;  // 列不允许拖动
    style?: any;
    onSortChange: (column: IMUIColumnType) => void;
}

// 调整table表头
const ResizableTitle = (props: IResizableTitle) => {
    const { column, onResize, children, resizeDisable, colResizeDisable, style = {}, onSortChange, ...restProps } = props
    const { headerColSpan, headerRowSpan, dataIndex, label, width, sorter, sortOrder } = column
    // 拖动的宽度(正在拖时才有值 拖完置为0)
    const [offset, setOffset] = useState<number>(0);

    const translateX = useMemo(() => {
        return offset;
    }, [offset]);

    const getTh = (thProps: any) => {
        return <TableCell
            key={dataIndex}
            variant="head"
            rowSpan={headerRowSpan}
            colSpan={headerColSpan}
            style={width ? {
                minWidth: width,
                width: width,
                maxWidth: width,
                ...style
            } : style}
            sx={{
                backgroundColor: 'background.paper',
            }}
            {...restProps}
            {...thProps}
        >
            <Row className="w100" align="middle" wrap={false}>
                <Col flex="auto" className="text_over_flow" title={typeof label === 'string' ? label : ''}>{thProps.children}</Col>
                {
                    sorter && (<Col flex="none" onClick={() => onSortChange(column)}>
                        <Tooltip title={getSortTitle(sorter, sortOrder)}>
                            {getTableSortIcon(sortOrder)}
                        </Tooltip>
                    </Col>)
                }
            </Row>
        </TableCell>
    }

    // 被合并的表头 未设置宽度 不允许拖动
    if (resizeDisable || colResizeDisable || column?.headerColSpan > 1 || !width) return getTh({
        children: label
    })

    return (
        <Resizable
            width={width + offset}
            // width={width}
            height={0}
            // onResize={onResize}
            // 操作手柄
            handle={
                <span
                    className={`react-resizable-handle ${offset ? 'active' : ''}`}
                    style={{ transform: `translateX(${translateX}px)` }}
                    onClick={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                    }}
                />
            }
            draggableOpts={{
                enableUserSelectHack: true, // 在调整大小期间不能选择元素内部的文本内容
                minConstraints: [TABLE_COL_MIN_WIDTH, 0],
                // maxConstraints: [width + nextColWidth, 0],
            }}
            onResizeStop={(e: React.SyntheticEvent, data: ResizeCallbackData) => {
                setOffset(0);
                onResize(e, data);
            }}
            onResize={(e: any, { size }: ResizeCallbackData) => {
                const currentOffset = size.width - width;
                // 限制拖动的最小宽度
                if (size.width < TABLE_COL_MIN_WIDTH) return setOffset(TABLE_COL_MIN_WIDTH - width)
                // 限制拖动的最大宽度
                // if (currentOffset > nextColWidth - TABLE_COL_MIN_WIDTH) return setOffset(nextColWidth - TABLE_COL_MIN_WIDTH);
                setOffset(currentOffset);
            }}
        >
            {
                getTh({
                    // onClick: (e: React.MouseEventHandler<HTMLTableCellElement>) => {
                    //     // @ts-ignore
                    //     if (!e.target?.className?.includes?.('react-resizable-handle')) restProps.onClick?.()
                    // },
                    children: (<div
                        style={{ width: "100%" }}
                        className="ofs-table-cell-wrapper"
                    >
                        <div className="ofs-table-cell">
                            {label}
                        </div>
                    </div>)
                })
            }
        </Resizable >
    )
}

export default ResizableTitle
